/**
 * 
 * @param {*} urlType 
 * @param {接口请求地址} url 
 * @param {接口请求类型} type 
 * @param {接口请求参数} date 
 * @param {接口请求头的携带信息，如不自定将某人携带token为请求头部} header 
 * @param (status === 0 为接口请求失败返回失败原因，并弹框展示) 
 * @param (status === 1 为接口请求成功返回成功响应数据) 
 * @param (status === 2 为接口请求成功，但是需要token校验，没有token返回登录页面重新授权登录回去token)
 *
 *
 */

let baseURL = 'http://127.0.0.1:8080/' //此处改成自己的域名


if (process.env.NODE_ENV === 'development') {
	baseURL = 'http://192.168.1.128:8088';
 
} else {
	baseURL = 'https://xxxx.com'; // 需要修改的域名,小程序必须要配置域名


}

/*所有api的路径统一管理*/
const apiPath = {
	// 答题
	dati: {
		// 热点题目
		showQuestionHot: baseURL + '/school_api/ceping/showQuestionHot',
		//题目种类
		showQuestionType: baseURL + '/school_api/ceping/showQuestionType',
		// 下一题
		showQuestionNext: baseURL + '/school_api/ceping/showQuestionNext',
		// 显示答案
		showAnswerById: baseURL + '/school_api/ceping/showAnswerById',
		// 根据id查询题目
		showQuestionById: baseURL + '/school_api/ceping/showQuestionById',
		// 连续答对题目数
		setContinuRight: baseURL + '/school_api/ceping/setContinuRight',

		// 显示排行榜
		showTop: baseURL + '/school_api/ceping/showTop',
		// 显示我的信息
		showMy: baseURL + '/school_api/ceping/showMy',

		// 内容识别,用户名违禁词识别
		riskgoText: baseURL + '/school_api/ceping/riskgoClientText',

		// 显示我的信息
		record: baseURL + '/school_api/ceping/record',
		// 签到
		signIn: baseURL + '/school_api/sign/signIn',
		// 历史记录
		recordHistory: baseURL + '/school_api/ceping/recordHistory',
	},
	common: {
		//问答
		question: baseURL + '/school_api/index/question',
		//查询每天多少配置
		questionDaysLimit: baseURL + '/school_api/index/questionDaysLimit',
		configInfo: baseURL + '/school_api/index/configInfo', //基础配置
		feedback: baseURL + '/school_api/index/feedback', // 反馈建议
		shareUser: baseURL + '/school_api/index/shareUser', // 分享加分
		// 减分
		useScore: baseURL + '/school_api/index/useScore',
		// 减分,传入积分
		useScoreNum: baseURL + '/school_api/index/useScoreNum',

		// 加分,需要传score参数
		plusScore: baseURL + '/school_api/index/plusScore',

	},
	questionList: {
		//热门话题
		showQuestion: baseURL + '/school_api/question/showQuestion',
		//详情
		showQuestionById: baseURL + '/school_api/question/showQuestionById',
		//我的历史数据
		showMyQuestion: baseURL + '/school_api/question/showMyQuestion',
		//点赞
		digg: baseURL + '/school_api/question/digg',

		//评论列表
		commentsList: baseURL + '/school_api/question/commentsList',
		//评论
		addComment: baseURL + '/school_api/question/addComment',
	},
	user: {
		//微信小程序登录
		miniAppLogin: baseURL + '/school_api/wxuser/login',

		//抖音小程序登录,只能获取openid
		dyLogin: baseURL + '/school_api/dyuser/login',

		//微信小程序登录,已经获取过openid
		miniAppLoginOpenid: baseURL + '/school_api/wxuser/loginByOpenid',
		//登出
		logout: baseURL + '/school_api/baseUser/logout',

		//修改是否展示问题
		updateStatus: baseURL + '/school_api/baseUser/updateStatus',

		//我的分享历史记录
		myShare: baseURL + '/school_api/baseUser/myShare',


	},
	wechat: {
		miniAppLogin: baseURL + '/wechat/miniAppLogin',
		mpLogin: baseURL + '/wechat/mpLogin',
		devLogin: baseURL + '/wechat/devLogin',
		mpConfig: baseURL + '/wechat/mpConfig',
	},
};


// 未获取token跳转的授权页面
const indexUrl = '/pages/main/index/index'

// 接口请求提示语句
const msg = '请稍候...'

// #ifdef MP-MP-WEIXIN
// 一起智慧闯关 appid 2024年7月14日
// 获取微信小程序的appId
let accountInfo = uni.getAccountInfoSync();
let miniAppid = accountInfo.miniProgram.appId;
console.log("manifest.json配置的微信小程序appId是：" + miniAppid);
// #endif


//智能robotsappid
//miniAppid = 'wxd68d22170aad7ef3'

const request = (urlType = '', url = '', type = '', data = {}, header = {}) => {
	var that = this
	if (JSON.stringify(header) == '{}') {
		header = {
			'Content-type': 'application/json',
			'sstoken': uni.getStorageSync('tokenValue')
		}
	}
	//始终加入对方的openid,可以判断用户是否违规使用
	let openid = uni.getStorageSync("openid");
	if (openid) {
		data.openid = openid;
	}

	// 检查URL中是否包含查询参数  
	if (url.includes('?')) {
		// 如果URL中已经有参数，则拼接 &openid=123  
		url = `${url}&openid=${openid}`;
	} else {
		// 如果URL中没有参数，则拼接 ?openid=123  
		url = `${url}?openid=${openid}`;
	}

	return new Promise((resolve, reject) => {

		//console.info(url+"  "+type+"  "+data)
		uni.request({
			method: type,
			url: url,
			data: data,
			header: header,
			dataType: 'json'
		}).then((response) => {
			//console.log('原始request的结果res',response)
			// uni.hideLoading();
			if (response[1].data.code == 200) {
				/* uni.showToast({
				    title: response[1].data.msg,
					icon: 'error',
				    duration: 2000
				}); */
				let [error, res] = response;

				resolve(res.data);
			} else if (response[1].data.code == 401) {
				uni.showToast({
					title: '请先登录',
					icon: 'error',
					duration: 2000,
					success: () => {}
				});
				reject(response[1].data)

				uni.switchTab({
					url: indexUrl
				})

			} else if (response[1].statusCode == 403) {
				uni.showToast({
					title: '请先登录',
					icon: 'error',
					duration: 2000,
					success: () => {}
				});
				uni.clearStorage();
				resolve(response[1].data)

			} else if (response[1].data.code == 500) {
				// let [error, res] = response;
				// resolve(res.data);
				uni.showToast({
					title: '系统错误,请联系管理员!',
					icon: 'error',
					duration: 2000,
					success: () => {}
				});
				resolve(response[1].data)
			}
		}).catch(error => {
			let [err, res] = error;
			reject(err)
			console.log(error[1].data)
			uni.showToast({
				title: error,
				icon: 'none',
				duration: 2000
			});
		})
	});

}
//post请求
const post = (url = '', data = {}) => {

	let method = 'POST';
	return new Promise((resolve, reject) => {
		//console.info('===>', url);

		request('', url, method, data).then(res => {
			//console.info('res结果是',url); 
			resolve(res)
		}, err => {
			reject(res)
		}).catch(error => {
			let [err, res] = error;
			reject(err)
			uni.showToast({
				title: error,
				icon: 'none',
				duration: 2000
			});
		});

	})

}

const get = (url = '', data = {}) => {

	let method = 'GET';
	return new Promise((resolve, reject) => {

		request('', url, method, data).then(res => {
			resolve(res)
		}, err => {
			reject(res)
		});

	})

}



/*无状态提示信息*/
const alert = function(msg = '', icon = 'none', url = '', openType = 'navigate') {
	/*消息强制转字符串*/
	if (typeof(msg) != 'string') {
		msg = msg.toString();
	}

	if (msg.length > 7) {
		//长度超过7个字符，用示模态弹窗展示
		uni.showModal({
			title: '提示',
			content: msg,
			showCancel: false
		});
	} else {
		if (icon == 'warning') {
			uni.showToast({
				title: msg,
				image: "/static/images/icon-warning.png"
			});
		} else {
			uni.showToast({
				title: msg,
				icon: icon
			})
		}
	}
	if (url || openType == 'back') {
		setTimeout(() => {
			if (openType == 'redirect') {
				uni.redirectTo({
					url: url
				});
			} else if (openType == 'switchTab') {
				uni.switchTab({
					url: url
				});
			} else if (openType == 'reLaunch') {
				uni.reLaunch({
					url: url
				});
			} else if (openType == 'back') {
				uni.navigateBack();
			} else {
				uni.navigateTo({
					url: url
				});
			}
		}, 1500)
	}
};

//小程序登录
const miniAppLogin = function() {

	// #ifdef MP-WEIXIN

	let openid = uni.getStorageSync("openid");
	//如果已经登录过
	if (openid) {
		post(apiPath.user.miniAppLoginOpenid + '?openid=' + openid).then(res => {
			loginToken(res.data); //登录
		})

	} else {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: function(loginRes) {
				console.log('loginRes', loginRes);
				//登录
				let data = {
					appid: miniAppid,
					code: loginRes.code
				}
				post(apiPath.user.miniAppLogin, data).then(res => {
					loginToken(res.data); //登录
					//回到首页
					/* uni.switchTab({
						url:'/pages/main/index/index'
					}) */
				})
			}
		});
	}



	// #endif


	// #ifdef MP-TOUTIAO
	uni.login({
		provider: 'toutiao', //使用抖音登录
		success: function(loginRes) {
			console.log('loginRes', loginRes);

			//登录
			let data = {
				appid: "tt715f07e2ee68cd7c01", // 甜心测评appid
				code: loginRes.code
			}
			post(apiPath.user.dyLogin, data).then(res => {
				//console.log("douyin小程序获得的openid", res.data);
				loginToken(res.data); //登录

			})
		}
	});
	// #endif

	//post(apiPath.user.miniAppLogin)
}

//登录
const loginToken = function(res) {
	if (res) {
		uni.setStorageSync("tokenName", res.tokenName);
		uni.setStorageSync("tokenValue", res.tokenValue);
		uni.setStorageSync("openid", res.openid);
		uni.setStorageSync("isLogin", 1);
		uni.setStorageSync("userInfo", res.userInfo)
		//分享时需要
		uni.setStorageSync("mySelfShareId", res.userInfo.id)
	}

}

//登出,注销
const logout = function() {
	uni.clearStorageSync()
	post(apiPath.user.logout).then(res => {
		if (res.code == 200) {
			alert('登出成功');
		}
	})
}


export default {
	request,
	post,
	apiPath,
	get,
	alert,
	miniAppLogin,
	logout
}